package cn.yangliu.nacos.comm.config.feign;

import java.io.IOException;

import cn.yangliu.nacos.comm.JsonResult;
import cn.yangliu.nacos.comm.enums.GlobalResultCode;
import cn.yangliu.nacos.comm.ex.GlobalException;
import cn.yangliu.nacos.comm.tools.JsonUtils;
import feign.Response;
import feign.Util;
import feign.codec.ErrorDecoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * The interface O auth error decoder.
 *
 * @author 问道于盲
 */
public class FeignErrorDecoder implements ErrorDecoder {

    /**
     * current class's static member
     * The constant LOGGER.
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(FeignErrorDecoder.class);

    /**
     * Instantiates a new O auth error decoder.
     * allow any class to create a new instance.
     */
    public FeignErrorDecoder() {
        LOGGER.info("Use FeignErrorDecoder implement!");
    }

    /**
     * Decode exception.
     *
     * @param methodKey the method key
     * @param response  the response
     * @return the exception
     */
    @Override
    public Exception decode(String methodKey, Response response) {
        int status = response.status();
        if (status == 404) {
            return new GlobalException(GlobalResultCode.INTERFACE_ADDRESS_NOT_FOUND);
        }
        try {
            String json = Util.toString(response.body().asReader());
            if (response.body() != null && JsonUtils.canDeserialize(json, JsonResult.class)) {
                LOGGER.error("Catch exception in feign decoding! Response is: {}", json);
                JsonResult<?> r = JsonUtils.jsonToObject(json, JsonResult.class);
                return new GlobalException(r.getCode(), r.getMsg());
            } else {
                LOGGER.error("Parse response body failed in feign decoding! Response is: {}", json);
                return new GlobalException(GlobalResultCode.UNSUPPORTED_RESPONSE_TYPE.getCode(),
						GlobalResultCode.UNSUPPORTED_RESPONSE_TYPE.getMsg().concat("! response is: ").concat(json));
            }
        } catch (IOException e) {
            LOGGER.error("Parse response body failed in feign decoding! {}", e.getMessage());
        }
        return new GlobalException(GlobalResultCode.FAILD);
    }
}
